package com.moteur.analysersite.performance;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class TailleSite {

	//private static Logger log = Logger.getLogger(TailleSite.class);
	
	public static double getTaille(String url) {
		double taille = 0;
		//new TailleSite().getWebSite();
		try {
			HttpURLConnection page = (HttpURLConnection) new URL(url).openConnection();
			taille = page.getContentLength();
			// le site a parser
			// exemple url "exemple.com"
			Document doc = Jsoup.connect(url)
					.timeout(30 * 1000).get();
			// Les selecteurs CSS
			//configurer au niveau Setters ou constructeur
			Elements contentsCss = doc.select("link[href]");
			Elements contentsJs = doc.select("script[src]");
			Elements contentsImg = doc.select("img[src]");
			// Objet TechnologieWR contient Information + Description
			for (Element elmnt : contentsCss) {
				HttpURLConnection content;
				if(elmnt.attr("href").contains("http")){
					content = (HttpURLConnection) new URL(elmnt.attr("href")).openConnection();
					//System.out.println("UrlCss: "+elmnt.attr("href"));
				}
				else{
					content = (HttpURLConnection) new URL(url+elmnt.attr("href")).openConnection();
					//System.out.println("UrlCss: "+url+elmnt.attr("href"));
				}
				taille += content.getContentLength();
			}
			
			for (Element elmnt : contentsJs) {
				HttpURLConnection content;
				if(elmnt.attr("src").contains("http")){
					content = (HttpURLConnection) new URL(elmnt.attr("src")).openConnection();
					//System.out.println("UrlJs: "+elmnt.attr("src"));
				}
				else{
					content = (HttpURLConnection) new URL(url+elmnt.attr("src")).openConnection();
					//System.out.println("UrlJs: "+url+elmnt.attr("src"));
				}
				taille += content.getContentLength();
			}
			
			for (Element elmnt : contentsImg) {
				//System.out.println("UrlImg: "+elmnt.attr("src"));
				HttpURLConnection content = (HttpURLConnection) new URL(url+elmnt.attr("src")).openConnection();
				taille += content.getContentLength();
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return Math.abs(taille);
	}
}

